package com.ylbh.modules.member.controller;

import com.ylbh.common.annotation.SysLog;
import com.ylbh.common.exception.NormalException;
import com.ylbh.common.pojo.member.dto.*;
import com.ylbh.common.pojo.member.dto.select.ExtractMoneyDetailSelectDTO;
import com.ylbh.common.pojo.member.dto.select.MemberSelectDTO;
import com.ylbh.common.pojo.member.dto.select.MerchantIncomeSelectDTO;
import com.ylbh.common.pojo.member.dto.update.MemberUpdateDTO;
import com.ylbh.common.pojo.member.vo.MemberVO;
import com.ylbh.common.pojo.member.vo.MerchantIncomeVO;
import com.ylbh.common.utils.*;
import com.ylbh.modules.member.service.MemberPlayerService;
import com.ylbh.modules.member.service.MemberService;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("member/user")
public class MemberController {
    @Autowired
    private MemberService memberService;
    @Autowired
    private MemberPlayerService memberPlayerService;

    /**
     * 获取会员列表
     */
    @RequestMapping("/queryUserList")
    @RequiresPermissions("member:user:queryUserList")
    public CommonResult<PageUtils> queryUserList(MemberSelectDTO params){
        PageUtils page = memberService.queryPage(params);
        return Ref.ok(page);
    }

    /**
     * 运营商列表
     */
    @RequestMapping("/queryOperatorList")
    @RequiresPermissions("member:operator:queryOperatorList")
    public CommonResult<PageUtils> queryOperatorList(PageDTO params){
        PageUtils page = memberService.queryOperatorPage(params);
        return Ref.ok(page);
    }

    /**
     * 通过id获取用户信息
     */
    @RequestMapping("/getUserById/{id}")
    @RequiresPermissions("member:user:getUserById")
    public CommonResult<MemberVO> getUserById(@PathVariable("id") Long id){
        MemberVO memberVO = memberService.getUserById(id);

        return Ref.ok(memberVO);
    }

    /**
     * 修改用户信息
     * @param memberDTO
     * @return
     */
    @SysLog("修改会员")
    @RequestMapping("/modifyById")
    @RequiresPermissions("member:user:modifyById")
    public CommonResult updateById(@RequestBody MemberDTO memberDTO){
		memberService.modifyByUserId(memberDTO);

        return Ref.ok();
    }

    /**
     * 开通超级会员
     */
    @SysLog("开通超级会员")
    @RequestMapping("/openNewPlayer/{id}")
    @RequiresPermissions("member:user:getUserById")
    public CommonResult openNewPlayer(@PathVariable Long id,@RequestBody Integer money, HttpServletRequest httpRequest){
        MemberUpdateDTO memberUpdateDTO = new MemberUpdateDTO();
        memberUpdateDTO.setReport(1);
        memberUpdateDTO.setId(id);
        // 修改大玩家状态
        memberService.modifyById(memberUpdateDTO);

        MemberDTO userEntity = memberService.getById(id);

        MemberPlayerDTO memberPlayerDTO = new MemberPlayerDTO();
        // 查询剩余次数
        Integer count = memberPlayerService.getCountByUserId(id);
        if(count == null){
            memberPlayerDTO.setPlayerCount(5);
        }else if(count==5){
            return Ref.error("该用户已经没有体验机会了！");
        }else {
            memberPlayerDTO.setPlayerCount(count-1);
        }
        Date date = new Date();

        memberPlayerDTO.setPlayerId(new IdWorker().nextId());
        memberPlayerDTO.setPlayerNo(IdWorker.getNoId().toString());
        memberPlayerDTO.setStartTime(date);
        memberPlayerDTO.setEndTime(DateUtils.addDateMonths(date,1));
        memberPlayerDTO.setParentId(userEntity.getParentId().intValue());
        memberPlayerDTO.setPlayerSrc("3");
        memberPlayerDTO.setCreateIp(IPUtils.getIpAddr(httpRequest));
        memberPlayerDTO.setIsPay("1");
        memberPlayerDTO.setPlayerMoney(new BigDecimal(money));
        memberPlayerDTO.setPayFrom("1");
        memberPlayerDTO.setState("1");
        memberPlayerDTO.setUserId(userEntity.getId().intValue());
        memberPlayerDTO.setCreateTime(date);
        memberPlayerService.save(memberPlayerDTO);
        return Ref.ok();
    }

    /**
     * 修改用户类型
     */
    @SysLog("修改用户类型")
    @RequestMapping("/updateUserType")
    @RequiresPermissions("member:user:getUserById")
    public CommonResult updateUserType(@RequestBody MemberUpgradeDTO upgradeDTO, HttpServletRequest httpServletRequest){
        upgradeDTO.setUpgradeIp(IPUtils.getIpAddr(httpServletRequest));
        upgradeDTO.setUpgradeId(new IdWorker().nextId());
        upgradeDTO.setUpgradeNo(DateHelper.getCurDateTime());
        upgradeDTO.setUpgradeSrc(3);
        upgradeDTO.setIsPay(true);
        upgradeDTO.setPayFrom(2);
        upgradeDTO.setState(true);
        Date date = new Date();
        upgradeDTO.setCreateTime(date);
        upgradeDTO.setSuccessTime(date);
        upgradeDTO.setEndTime(date);
        upgradeDTO.setStartTime(date);
        upgradeDTO.setLatLng("113.307649,23.224816");
        upgradeDTO.setIsCommission("0");
        upgradeDTO.setGivingIntegral(0);
        String msg = memberService.modifyUserType(upgradeDTO);
        if ("修改类型成功".equals(msg))
            return Ref.ok(msg);
        else
            return Ref.error(msg);
//        return Ref.error("暂未提供类型修改");
    }

    /**
     * 提现明细
     */
    @RequestMapping("/queryExtractMoneyDetailList")
    @RequiresPermissions("member:user:getUserById")
    public CommonResult<PageUtils> queryExtractMoneyDetailList(ExtractMoneyDetailSelectDTO params){
        PageUtils pageUtils = memberService.queryBusinessWithRecordList(params);
        return Ref.ok(pageUtils);
    }

    /**
     * 商户收益
     */
    @RequestMapping("/queryMerchantIncomeList")
    @RequiresPermissions("member:user:getUserById")
    public CommonResult<MerchantIncomeVO> merchantIncomeList(MerchantIncomeSelectDTO params){
        // 获取数据
        PageUtils pageUtils = memberService.queryMerchantIncomeList(params);
        //汇总数据
        Long id = Long.valueOf(params.getWithUserId());
        BigDecimal sumMoney = memberService.sumMerchantIncomeMoney(id);
        //汇总商户推广提现未提现余额
        HashMap<String,BigDecimal> moneyMap = memberService.sumMerchantExtensionMoney(id);

        moneyMap.put("profit",sumMoney);

        MerchantIncomeVO merchantIncomeVO = new MerchantIncomeVO();
        merchantIncomeVO.setData(pageUtils);
        merchantIncomeVO.setExtensionMoney(moneyMap);

        return Ref.ok(merchantIncomeVO);
    }

    @SysLog("导出会员详情")
    @RequestMapping("userExcel")
    public CommonResult<Void> userExcel(HttpServletResponse response, HttpServletRequest request) throws NormalException {
        memberService.userExcel(response, request);
        return Ref.ok();
    }

    @ApiOperation("获取运营商是否添加过")
    @GetMapping("getIsExistenceByUserName/{userName}")
    public CommonResult getIsExistenceByUserName(@PathVariable String userName) {
        int count = memberService.getIsExistenceByUserName(userName);
        return Ref.ok(count);
    }

    @SysLog("新增运营商")
    @ApiOperation("新增运营商")
    @RequestMapping("/addOperator")
    @RequiresPermissions("member:user:addOperator")
    public CommonResult<Void> addOperator(@RequestBody AddOperatorDTO  addOperatorDTO){
        memberService.addOperator(addOperatorDTO);
        return Ref.ok();
    }

    @ApiOperation("会员关系")
    @RequestMapping("queryMembership")
    @RequiresPermissions("member:user:queryMembership")
    public CommonResult<PageUtils> queryMembership(MembershipDTO dat) {
        PageUtils membership = memberService.queryMembership(dat);
        return Ref.ok(membership);
    }

    @ApiOperation("会员升级-判断是否需要选择上级")
    @GetMapping("needToSelectSuperiorById/{id}")
    public CommonResult needToSelectSuperiorById(@PathVariable Long id) {
        MemberVO isSelect = memberService.needToSelectSuperiorById(id);
        return Ref.ok(isSelect);
    }

    @ApiOperation("获取所有的运营商")
    @GetMapping("queryAllOperator")
    public CommonResult queryAllOperator() {
        List<MemberVO> vo = memberService.queryAllOperator();
        return Ref.ok(vo);
    }
}
